<?php

use App\Enums\AssetSourceType;
use App\Enums\AssetStatus;
use App\Enums\TokenLockType;
use App\Enums\TokenStatus;
use App\Enums\TransStatus;
use App\Models\Asset;
use App\Models\ProductToken;

require __DIR__ . '/../vendor/autoload.php';

$app = require_once __DIR__ . '/../bootstrap/app.php';

$app->make(\App\Console\Kernel::class)->bootstrap();

/* ============== Write Codes Below ================= */

$walletService = app()->get(\App\Services\WalletService::class);
$orderNo = 'S202208301104518975';
$order = \App\Models\Order::query()->where('order_no', $orderNo)->first();

$tokens = ProductToken::query()
    ->where('lock_refer_id', $order->id)->where('lock_type', TokenLockType::ORDER)
    ->whereIn('status', [TokenStatus::FAILED, TokenStatus::LOCKED])
    ->get();
$contractAddress = $order->product->contract_address;
$user = $order->user;

echo 'TOKEN数量：' . count($tokens) . PHP_EOL;

foreach ($tokens as $token) {
    $trans = $walletService->tokenTransList(
        $contractAddress,
        $token->token_id,
    );
    if ($trans[0]['holder'] == $user->mobile) {
        $transHash = $trans[0]['transHash'];
    } else {
        $transResult = $walletService->transfer(
            '',
            $contractAddress,
            [$token->token_id],
            $user->wallet_address
        );
        $transHash = Arr::get($transResult, $token->token_id, 'trans_hash_not_return');
    }
    $token->status = TokenStatus::SOLD;
    $token->save();

    // 保存资产信息
    $asset = new Asset();
    $asset->user_id = $order->user_id;
    $asset->source_type = AssetSourceType::ORDER;
    $asset->source_id = $order->id;
    $asset->contract_address = $order->product->contract_address;
    $asset->token_id = $token->token_id;
    $asset->trans_hash = $transHash;
    $asset->asset_status = AssetStatus::HOLD;
    $asset->save();

    echo $token->token_id . '处理成功' . PHP_EOL;
}

$order->trans_status = TransStatus::SUCCESS;
$order->trans_fail_reason = '';
$order->save();
